<template>
  <div class="custom-form">
    <el-row :gutter="15">
      <el-form ref="elForm" :model="formData" :rules="rules" size="medium" label-width="100px"
        :key="showFormKey" v-if="showForm">
        <el-col :span="24" v-show="hasFormPermission('order_number')">
          <el-form-item :label="$t('合同编号')" prop="order_number">
            <el-input v-model="formData['order_number']" placeholder="合同编号"
              :disabled="hasDisabledPermission('order_number',true)"
              :readonly="!hasEditPermission('order_number',true)" :style="{width: '100%'}"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24" v-show="hasFormPermission('business_opportunity_number')">
          <el-form-item :label="$t('商机选择')" prop="business_opportunity_number">
            <el-input v-model="formData['business_opportunity_number_showValue']" placeholder="请输入商机选择"	
              :disabled="hasDisabledPermission('business_opportunity_number',false)"
              :readonly="!hasEditPermission('business_opportunity_number',false)" clearable
              suffix-icon='el-icon-more' :style="{width: '100%'}"
              @focus='mutipleHandlerClick(autoHandlerClickConfig(103))'
              @clear="clearBombLayerFormData('business_opportunity_number')"></el-input>
            <el-form-item prop="business_opportunity_number" style="display:none">
              <el-input v-model="formData['business_opportunity_number']"></el-input>
            </el-form-item>
          </el-form-item>
        </el-col>
        <avue-filterable-data-list type="mutiple" :conf="mutipleCompleteConf"
          v-if="mutipleCompleteDialogVisible" v-on:onHandler="mutipleFilterableCallBack">
        </avue-filterable-data-list>
        <el-col :span="24" v-show="hasFormPermission('customer_id')">
          <el-form-item :label="$t('企业名称')" prop="customer_id">
            <el-input v-model="formData['customer_id']" placeholder="请输入企业名称"
              :disabled="hasDisabledPermission('customer_id',this.customer_id_disabled)"
              :readonly="!hasEditPermission('customer_id',this.customer_id_readonly)" clearable :style="{width: '100%'}">
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24" v-show="hasFormPermission('contactor_name')">
          <el-form-item :label="$t('联系人姓名')" prop="contactor_name">
            <el-input v-model="formData['contactor_name']" placeholder="请输入联系人姓名"
              :disabled="hasDisabledPermission('contactor_name',false)"
              :readonly="!hasEditPermission('contactor_name',false)" clearable :style="{width: '100%'}">
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24" v-show="hasFormPermission('contactor_phone')">
          <el-form-item :label="$t('联系方式')" prop="contactor_phone">
            <el-input v-model="formData['contactor_phone']" placeholder="请输入联系方式"
              :disabled="hasDisabledPermission('contactor_phone',false)"
              :readonly="!hasEditPermission('contactor_phone',false)" clearable :style="{width: '100%'}">
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24" v-show="hasFormPermission('create_date')">
          <el-form-item :label="$t('订单签订日期')" prop="create_date">
            <el-date-picker :disabled="hasDisabledPermission('create_date',false)"
              :readonly="!hasEditPermission('create_date',false)" v-model="formData['create_date']"
              format="yyyy-MM-dd" value-format="yyyy-MM-dd" :style="{width: '100%'}" placeholder="请选择订单签订日期"
              clearable></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="24" v-show="hasFormPermission('sales_man_id')">
          <el-form-item :label="$t('服务商')" prop="sales_man_id">
            <el-input v-model="formData['sales_man_id']" placeholder="请输入服务商"
              :disabled="hasDisabledPermission('sales_man_id',true)"
              :readonly="!hasEditPermission('sales_man_id',true)" clearable :style="{width: '100%'}">
            </el-input>
          </el-form-item>
        </el-col>
		<el-col :span="24" v-show="hasFormPermission('general_contractor')">
		      <el-form-item :label="$t('上级总包商')" prop="general_contractor">
		        <el-select v-model="formData['general_contractor']" placeholder="请选择上级总包商"
		          :disabled="hasDisabledPermission('general_contractor',false)" filterable clearable
		          :style="{width: '100%'}">
		          <el-option v-for="(item, index) in general_contractorOptions" :key="index" :label="item.F_ItemName"
		            :value="item.F_ItemValue" :disabled="item.disabled"></el-option>
		        </el-select>
		      </el-form-item>
		    </el-col>
        <el-col :span="24" v-show="hasFormPermission('contract_number')">
          <el-form-item :label="$t('销售合同号')" prop="contract_number">
            <el-input v-model="formData['contract_number']" placeholder="请输入合同号"
              :disabled="hasDisabledPermission('contract_number',false)"
              :readonly="!hasEditPermission('contract_number',false)" clearable :style="{width: '100%'}">
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24" v-show="hasFormPermission('contract_name')">
          <el-form-item :label="$t('销售合同名称')" prop="contract_name">
            <el-input v-model="formData['contract_name']" placeholder="请输入销售合同名称"
              :disabled="hasDisabledPermission('contract_name',false)"
              :readonly="!hasEditPermission('contract_name',false)" clearable :style="{width: '100%'}">
            </el-input>
          </el-form-item>
        </el-col>
        <!-- <el-col :span="24" v-show="hasFormPermission('field1130899')">
          <el-form-item :label="$t('合同日期范围')" prop="field1130899">
            <el-date-picker :disabled="hasDisabledPermission('field1130899',false)"
              :readonly="!hasEditPermission('field1130899',false)" type="daterange"
              v-model="formData['field1130899']" format="yyyy-MM-dd" value-format="yyyy-MM-dd"
              :style="{width: '100%'}" start-placeholder="开始日期" end-placeholder="结束日期" range-separator="至"
              clearable></el-date-picker>
          </el-form-item>
        </el-col> -->
		<el-col :span="12" v-show="hasFormPermission('contract_start_date')">
		  <el-form-item :label="$t('合同开始日期')" prop="contract_start_date">
		    <el-date-picker :disabled="hasDisabledPermission('contract_start_date',false)"
		      :readonly="!hasEditPermission('contract_start_date',false)" v-model="formData['contract_start_date']"
		      format="yyyy-MM-dd" value-format="yyyy-MM-dd" :style="{width: '100%'}" placeholder="请选择合同开始日期"
		      clearable></el-date-picker>
		  </el-form-item>
		</el-col>
		<el-col :span="12" v-show="hasFormPermission('contract_end_date')">
		  <el-form-item :label="$t('合同结束日期')" prop="contract_end_date">
		    <el-date-picker :disabled="hasDisabledPermission('contract_end_date',false)"
		      :readonly="!hasEditPermission('contract_end_date',false)" v-model="formData['contract_end_date']"
		      format="yyyy-MM-dd" value-format="yyyy-MM-dd" :style="{width: '100%'}" placeholder="请选择合同结束日期"
		      clearable></el-date-picker>
		  </el-form-item>
		</el-col>
        <el-col :span="12" v-show="hasFormPermission('tax_amount')">
          <el-form-item :label="$t('合同金额(含税)')" prop="tax_amount">
            <el-input v-model="formData['tax_amount']" placeholder="请输入合同金额(含税)"
              :disabled="hasDisabledPermission('tax_amount',false)"
              :readonly="!hasEditPermission('tax_amount',false)" clearable :style="{width: '100%'}">
              <template slot="append">元</template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12" v-show="hasFormPermission('none_tax_amount')">
          <el-form-item :label="$t('合同金额(不含税)')" prop="none_tax_amount">
            <el-input v-model="formData['none_tax_amount']" placeholder="请输入合同金额(不含税)"
              :disabled="hasDisabledPermission('none_tax_amount',false)"
              :readonly="!hasEditPermission('none_tax_amount',false)" clearable :style="{width: '100%'}">
              <template slot="append">元</template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24" v-show="hasFormPermission('contract_instruction')">
          <el-form-item :label="$t('合同主要内容说明')" prop="contract_instruction">
            <el-input v-model="formData['contract_instruction']" type="textarea" placeholder="请输入合同主要内容说明"
              :disabled="hasDisabledPermission('contract_instruction',false)"
              :readonly="!hasEditPermission('contract_instruction',false)" :autosize="{minRows: 4, maxRows: 4}"
              :style="{width: '100%'}"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24" v-show="hasFormPermission('files')">
          <el-form-item :label="$t('附件')" prop="files">
            <xjr-custom-upload :config="filesConfig"
              :disabled="hasDisabledPermission('files',false)" v-model="formData['files']"
              list-type="picture-card"></xjr-custom-upload>
          </el-form-item>
        </el-col>
        <el-col :span="24" v-show="hasLookFormPermission('field118ced0')">
          <el-form-item label-width="0" prop="field118ced0">
            <h2 align='center' style="color:undefined;font-size: 14px;text-align: left"
              :style="{width: '100%'}">合同审阅</h2>
          </el-form-item>
        </el-col>
        <el-col :span="8" v-show="hasFormPermission('state')">
          <el-form-item :label="$t('审阅结果')" prop="state">
            <el-radio-group v-model="formData['state']" size="medium"
              :disabled="hasDisabledPermission('state',true)"
              :readonly="!hasEditPermission('state',true)">
              <el-radio v-for="(item, index) in stateOptions" :key="index" :label="item.F_ItemValue"
                :disabled="item.disabled">{{item.F_ItemName}}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="8" v-show="hasFormPermission('auditor_id')">
          <el-form-item :label="$t('审阅人')" prop="auditor_id">
            <el-input v-model="formData['auditor_id']" placeholder="请输入审阅人"
              :disabled="hasDisabledPermission('auditor_id',true)"
              :readonly="!hasEditPermission('auditor_id',true)" clearable :style="{width: '100%'}">
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8" v-show="hasFormPermission('audit_date')">
          <el-form-item :label="$t('审阅时间')" prop="audit_date">
            <el-date-picker :disabled="hasDisabledPermission('audit_date',true)"
              :readonly="!hasEditPermission('audit_date',true)" v-model="formData['audit_date']"
              format="yyyy-MM-dd" value-format="yyyy-MM-dd" :style="{width: '100%'}" placeholder="请选择审阅时间"
              clearable></el-date-picker>
          </el-form-item>
        </el-col>
		<el-col :span="24" v-show="hasFormPermission('reject_reason')" v-if="this.isreject_reason">
		  <el-form-item :label="$t('不通过原因')" prop="reject_reason">
		    <el-input v-model="formData['reject_reason']" type="textarea" placeholder="请输入不通过原因"
		      :disabled="hasDisabledPermission('reject_reason',true)"
		      :readonly="!hasEditPermission('reject_reason',true)" :autosize="{minRows: 4, maxRows: 4}"
		      :style="{width: '100%'}"></el-input>
		  </el-form-item>
		</el-col>
        <el-col :span="24" >
          <el-form-item size="large" v-if="isEdit" class="form-button-center">
            <el-button type="primary" @click="submitForm" :loading="submitLoading">
              {{submitLoading?$t('workFlow.WFMenu.hintSubmit'):$t('submit')}}</el-button>
            <el-button @click="cancelForm">{{$t('cancelText')}}</el-button>
          </el-form-item>
        </el-col>
      </el-form>
    </el-row>
  </div>
</template>
<script>

        import authorizeMixin from "@/mixins/authorize";
        import { baseUrl } from "@/config/env";
        import request from "@/router/axios";
         import {fieldsConfig,formFieldsMap,getHideComponents} from './SalesContractConfig'
		import { formValidateNotice } from '@/util/util';
        export default {
          mixins: [authorizeMixin],
       
  components: {},
  props: ['keyValue', 'isEdit', 'disabled'],
  data() {
    return {
      userInfo: {},
      submitLoading: false,
      showForm: true,
      showFormKey: 1,
      reRenderSubform: false,
      operationVal: 'add',
      isAdd: true,
	  customer_id_disabled:false,
	  customer_id_readonly:false,
	  isreject_reason:false,
      addressUrl:'sales_order',
      autoCompleteConfEventData: [],
      mainTableName: 'sales_order',
      formConfig: {},
      formFieldsMap: new Map(),
      hideComponentsMap: new Map(),
      needShowValueTags: ['asso-popup', 'mutiple-popup'],
      mutipleCompleteConf: {},
      mutipleCompleteDialogVisible: false,
      formData: {
        'order_number': '',
        'business_opportunity_number_showValue': '',
        'business_opportunity_number': '',
        'customer_id': '',
        'contactor_name': '',
        'contactor_phone': '',
        'create_date': null,
        'sales_man_id': localStorage.getItem('sales_man_id'),
		'general_contractor':'',
        'contract_number': '',
        'contract_name': '',
        // 'field1130899': [],
		'contract_start_date':'',
		'contract_end_date':'',
        'tax_amount': '',
        'none_tax_amount': '',
        'contract_instruction': '',
        'files': null,
        // 'field118ced0': '',
        'state': '2',
        'auditor_id': '',
        'audit_date': null,
		'reject_reason':'',
      },
      rules: {
        order_number: [],
        business_opportunity_number: [],
        customer_id: [{
          required: true,
          message: '请输入企业名称',
          trigger: 'blur'
        }],
        contactor_name: [{
          required: true,
          message: '请输入联系人姓名',
          trigger: 'blur'
        }],
        contactor_phone: [{
          required: true,
          message: '请输入联系方式',
          trigger: 'blur'
        }],
        create_date: [{
          required: true,
          message: '请选择订单签订日期',
          trigger: 'change'
        }],
        sales_man_id: [{
          required: true,
          message: '请输入服务商',
          trigger: 'blur'
        }],
        contract_number: [{
          required: true,
          message: '请输入合同号',
          trigger: 'blur'
        }],
        contract_name: [{
          required: true,
          message: '请输入销售合同名称',
          trigger: 'blur'
        }],
        // field1130899: [{
        //   required: true,
        //   type: 'array',
        //   message: '请至少选择一个合同日期范围',
        //   trigger: 'change'
        // }],
		contract_start_date: [{
		  required: true,
		  message: '请选择合同开始日期',
		  trigger: 'change'
		}],
		contract_end_date: [{
		  required: true,
		  message: '请选择合同结束日期',
		  trigger: 'change'
		}],
        tax_amount: [{
          required: true,
          message: '请输入合同金额(含税)',
          trigger: 'blur'
        }],
        none_tax_amount: [{
          required: true,
          message: '请输入合同金额(不含税)',
          trigger: 'blur'
        }],
        contract_instruction: [{
          required: true,
          message: '请输入合同主要内容说明',
          trigger: 'blur'
        }],
        files: [{
          required: true,
          message: '上传不能为空',
          trigger: 'change'
        }],
        state: [{
          required: true,
          message: '审阅结果不能为空',
          trigger: 'change'
        }],
        auditor_id: [],
        audit_date: [],
		reject_reason: [],
      },
      business_opportunity_numberOptions: [],
	  general_contractorOptions:[],
      filesConfig: {
        "showTip": true,
        "fileSize": 10,
        "sizeUnit": "MB",
        "buttonText": "点击上传",
        "disabled": false,
        "multiple": false,
      },
      stateOptions: [],
    }
  },
  computed: {},
  watch: {},
  async created() {
    this.formConfig = this.getFormConfig();
    this.formFieldsMap = this.getFormFieldsMap();
    this.userInfo = localStorage.getItem("avue-userInfo") ? JSON.parse(localStorage.getItem(
      "avue-userInfo")).content : {};
	console.log(this.hasDisabledPermission('customer_id',false))
  },
  async mounted() {
    this.hideComponentsMap = await this.getHideComponentsMap();
    this.showForm = false;
    await this.insertCreatedEvent();
    //TODO   再这里做数据回填 请求表单数据
   
           if(this.keyValue){
              this.isAdd = false;
          }
           if(!this.isAdd&&this.keyValue){
              this.operationVal = 'edit';
              try {
                let res = await request({
                  url: baseUrl + "/"+this.addressUrl+"/" + this.keyValue,
                  method: "get",
                });
                  
            this.formData = res.data.data
            if(res.data.data.state == 0){
				this.formData.state = '0'
			}
			if(res.data.data.state == 1){
				this.formData.state = '1'
				this.isreject_reason = true
			}
			if(res.data.data.state == 2){
				this.formData.state = '2'
			}
				if(this.formData.business_opportunity_number){
					this.$set(this.formData,'business_opportunity_number_showValue',this.formData.business_opportunity_number)
          let config=this.autoHandlerClickConfig(103);
				  this.getMutipleAllData(this.formData,config,'business_opportunity_number',103);
				}
				
            // if(res.data.data.field1130899){
            //     this.formData.field1130899 = res.data.data.field1130899.split(',')
            // }else{
            //   this.formData.field1130899 = [];
            // }
            
                  await this.handleEdit();
                 this.showFormKey++;
              } catch (error) {
              }
          }

       
    if (typeof this.getField104Options == "function" && this.operationVal == 'add') {
      await this.getField104Options();
    }
    if (typeof this.getField103Options == "function") {
      await this.getField103Options();
    }
    if (typeof this.getField120Options == "function") {
      await this.getField120Options();
    }
	if (typeof this.getField100Options == "function") {
	      await this.getField100Options();
	    }
    await this.insertMountedEvent();
    this.reRenderSubform = true; //子表单显示
    this.showFormKey++;
    this.processParameterAssignment();
    this.showForm = true;
  },
  methods: {
    getFormData() {
      let key = this.mainTableName + 'Entity';
      let returnParams = {};
      returnParams[key] = this.formData;
      return {
        ...returnParams,
      };
    },
	// changeValue(e){
	// 	console.log(e)
	// },
    validateForm() {
      this.$refs['elForm'].validate(valid => {});
    },
    async aysncValidateForm() {
      let validataArry = []
      let formValidateNotice = function formValidateNotice(obj, that, formAuth) {
        for (var o in obj) {
          if (!formAuth[o] && obj[o][0]) {
            that.$message({
              message: obj[o][0].message + ',' + that.$t('noFormAuth'),
              type: 'warning'
            });
            return;
          }
        }
      }
      validataArry.push(new Promise((resolve, reject) => {
        this.$refs['elForm'].validate((valid, object) => {
          if (!this.isWorkflowForm) formValidateNotice(object, this, this.formEnCodeList)
          resolve(valid)
        })
      }))
      let res = await Promise.all(validataArry)
      if (res.includes(false)) {
        return false
      }
      else {
        return true;
      }
    },
    changeTableData() {
      // if (this.formData.field1130899 instanceof Array) this.formData.field1130899 = this.formData.field1130899
      //   .join(',')
    },
    async submitForm() {
      this.submitLoading = true;
      let valid = await this.aysncValidateForm();
      if (valid == false) {
        this.submitLoading = false;
        return false;
      }
      this.changeTableData();
      //格式化数据
      let newObj = this.getFormData();
      
        //如果没有传入参数就是新增
        if (!this.keyValue) {

          request({
            url: baseUrl + "/"+this.addressUrl,
            method: "post",
            data : newObj
          }).then((res) => {
            this.submitLoading = false;
            this.$notify({
              title: "成功",
              message: "新增成功",
              type: "success",
            });
             this.$emit("onChange",true)
          });

        }
        else{

         request({
            url: baseUrl + "/"+this.addressUrl+"/" + this.keyValue,
            method: "put",
            data : newObj
          }).then((res) => {
            this.submitLoading = false;
            this.$notify({
              title: "成功",
              message: "修改成功",
              type: "success",
            });
             this.$emit("onChange",true)
          });

        }
       
       
      
      
      await this.handleSubmit();
    },
    cancelForm() {
      this.$emit("onChange", true)
    },
    formatTree(data, valueField, lableField, childField, type) {
      let tree = [];
      data.forEach((node, index) => {
        let newNode = {
          value: node[valueField],
          label: node[lableField],
        };
        if (type) {
          newNode.disabled = node[valueField] == undefined ? true : false
        }
        tree.push(newNode);
        if (node[childField] != null && node[childField].length > 0) {
          newNode.children = (this.formatTree(node[childField], valueField, lableField, childField,
          type));
        }
      }, this);
      return tree;
    },
    
          //辅助编辑 预留方法
          async handleEdit() {
            await this.insertEditEvent();
          },
          
    //FORM_EVENT_EDIT
    
        //辅助提交 预留方法
        async handleSubmit() {
          await this.insertSubmitEvent();
        },
        //辅助工作流提交 预留方法
        getHandleSubmitFormEvent() {
            
        },
        //辅助工作流表单事件 判断 表单事件是否已经执行过
        getisExecutedFormEvent() {
            let key = 'index'+this.$store.state.formParser.workflowFormTabIndexKey;
            return this.$store.state.formParser.isExecutedFormEvent[key]?this.$store.state.formParser.isExecutedFormEvent[key]:false;
            
        },
      
    async getField104Options() {
      // 注意：this.$axios是通过Vue.prototype.$axios = axios挂载产生的
      try {
        let resp = await this.$axios({
          method: 'get',
          url:  baseUrl + '/code-rules/SalesContract/gen',
        });
        if (resp.data.data) {
          this.formData.order_number = resp.data.data;
        }
      }
      catch (error) {}
    },
    mutipleFilterableCallBack(data) {
      if (!this.mutipleCompleteConf) {
        return false;
      }
      let saveField = this.mutipleCompleteConf.dataType == 'dataItem' ? 'F_ItemValue' : this
        .mutipleCompleteConf.saveField
      let showField = this.mutipleCompleteConf.dataType == 'dataItem' ? 'F_ItemName' : this
        .mutipleCompleteConf.showField
      //弹窗关闭前回填数据  如果有选择数据项
      if (data && data.length > 0) {
        let arr = [],
          arr1 = []
        data.forEach(it => {
          arr.push(it[showField]);
          arr1.push(it[saveField]);
        })
        this.formData[this.mutipleCompleteConf.model + '_showValue'] = arr.join(',');
        this.formData[this.mutipleCompleteConf.model] = arr1.join(',');
		
		let a = data[0].需求企业名称;
		if(data.length < 2){
			this.formData.customer_id = data[0].需求企业名称;
			this.customer_id_disabled = true;
			this.customer_id_readonly = true;
		}
		else{
			for(t = 1; t < data.length; t++){
				
				if(a == data[t].需求企业名称)
				{
					this.formData.customer_id = data[0].需求企业名称;
					this.customer_id_disabled = true;
					this.customer_id_readonly = true;
				}
				else{
					this.$notify({
					  title: "失败",
					  message: "商机非同一家企业,请重新选择",
					  type: "warning",
					});
				}
			}
		}
      }
      if (this.autoCompleteConfEventData && this.autoCompleteConfEventData.length > 0) {
        this.triggerEventHandler(this.autoCompleteConfEventData);
		
      }
      //更新表单校验
      this.$refs['elForm'].validate(valid => {
        console.log('更新表单校验 valid', valid);
      })
      //关闭弹窗
		  this.mutipleCompleteDialogVisible = false;
    },
    mutipleHandlerClick(conf) {
      if (conf.eventData && conf.eventData.length > 0) {
        this.autoCompleteConfEventData = conf.eventData;
		
      }
      else {
        this.autoCompleteConfEventData = conf.eventData;
      }
      this.mutipleCompleteConf.title = conf.label + '-选择记录';
      this.mutipleCompleteConf.model = conf.model;
	  
      this.mutipleCompleteConf.formId = conf.formId;
      this.mutipleCompleteConf.dataType = conf.dataType;
	  // console.log(conf.dataType)
      switch (conf.dataType) {
        case 'dataSource':
          this.mutipleCompleteConf.dataSource = conf.dataSource;
		  // this.mutipleCompleteConf.keyword = '123';
          this.mutipleCompleteConf.tabName = 'base';
		  
          break;
        case 'dataSql':
          this.mutipleCompleteConf.dataSource = conf.database;
          this.mutipleCompleteConf.tabName = 'sql';
          this.mutipleCompleteConf.sqlStr = conf.sql;
          break;
        case 'dataItem':
          this.mutipleCompleteConf.dataSource = conf.dataItem;
          this.mutipleCompleteConf.dataItem = conf.dataItem;
          this.mutipleCompleteConf.fields = ['F_ItemName', 'F_ItemValue'];
          break;
        case 'dataApi':
          this.mutipleCompleteConf.apiConfig = conf.apiConfig;
          this.mutipleCompleteConf.formFieldsMap = this.formFieldsMap;
          this.mutipleCompleteConf.formData = this.formData;
          this.mutipleCompleteConf.tabName = 'api';
          break;
          conf.showField = 'F_ItemName';
          conf.saveField = 'F_ItemValue';
          this.mutipleCompleteConf.tabName = 'item';
          break;
      }
      this.mutipleCompleteConf.showField = conf.showField;
	  
      this.mutipleCompleteConf.saveField = conf.saveField;
      this.mutipleCompleteConf.autoBindFields = conf.autoBindFields;
	  // console.log(conf.autoBindFields)
      this.mutipleCompleteConf.defaultValue = this.formData[conf.model];
      this.mutipleCompleteDialogVisible = true;
    },
    //多选弹层 表单编辑时数据回显处理
    getMutipleAllData(formData, config, model, formId) {
      let datatype = config.dataType;
      let saveField = datatype == 'dataItem' ? 'F_ItemValue' : config.saveField
      let showField = datatype == 'dataItem' ? 'F_ItemName' : config.showField;
      if (datatype == 'dataSource' || datatype == 'dataSql') {
        if (config.dataSource) {
          this.changeMutipleData(formData,  baseUrl + '/data-sources/' + config.dataSource +
            '/data', model, saveField, showField)
        }
      }
      if (datatype == 'dataItem') {
        this.changeMutipleData(formData,  baseUrl + '/data-items/' + config.dataItem +
          '/detail', model, saveField, showField)
      }
      if (datatype == 'dataApi') {
        let config = this.autoHandlerClickConfig(formId);
        if (config.apiConfig) {
          this.changeMutipleDataFromApi(config.apiConfig, model);
        }
      }
    },
    autoHandlerClickConfig(formId) {
      return this.formFieldsMap.get(formId).__config__.autoHandlerConfig;
    },
    async changeMutipleDataFromApi(apiConfig, model) {
      let url =  baseUrl + '' + apiConfig.url;
      let res = await this.$axios({
        method: 'POST',
        url: url,
        headers: {},
        params: {},
        data: {},
      });
      if (res.data.data && apiConfig.dataSource && res.data.data[apiConfig.dataSource].length > 0 &&
        apiConfig.saveField) {
        let arr = this.formData[model].split(',');
        let arr1 = [];
        arr.forEach(it => {
          let temp = res.data.data[apiConfig.dataSource].find(o => {
            return o[apiConfig.saveField] == it
          });
          if (temp) {
            arr1.push(temp[apiConfig.showField])
          }
        })
        if (arr1.length > 0) {
          this.formData[model + '_showValue'] = arr1.join(',');
		  
        }
      }
    },
    async changeMutipleData(formData, url, model, saveField, showField) {
      try {
        let resp = await this.$axios({
          method: 'get',
          url: url,
		  
        });
        if (resp.data.data) {
			
          let arr = formData[model].split(',');
          let arr1 = [];
          arr.forEach(it => {
            let temp = resp.data.data.find(o => {
              return o[saveField] == it
            });
            if (temp) {
              arr1.push(temp[showField])
            }
          })
          if (arr1.length > 0) {
            formData[model + '_showValue'] = arr1.join(',');
			
          }
        }
      }
      catch (error) {}
    },
    async getField120Options() {
      // 注意：this.$axios是通过Vue.prototype.$axios = axios挂载产生的
      try {
        let resp = await this.$axios({
          method: 'get',
          url:  baseUrl + '/data-items/SHJG/detail',
        });
        if (resp.data.data) {
          this.stateOptions = resp.data.data;
        }
      }
      catch (error) {}
    },
	async getField100Options() {
	      // 注意：this.$axios是通过Vue.prototype.$axios = axios挂载产生的
	      try {
	        let resp = await this.$axios({
	          method: 'get',
	          url: baseUrl + '/data-items/ZBS/detail',
	        });
	        if (resp.data.data) {
	          this.general_contractorOptions = resp.data.data;
	        }
	      }
	      catch (error) {}
	    },
    async triggerEventHandler(eventData) {
      if (eventData.length > 0) {
        eventData.forEach(ele => {
          let functionName = 'getField' + ele.componentFormId + 'Options';
          if (typeof this[functionName] == "function") {
            this[functionName]();
          }
        })
      }
    },
    triggerEventFormIdHandler(formId) {
      if (this.formFieldsMap.get(formId).__config__.triggerEvents && this.formFieldsMap.get(formId).__config__
        .triggerEvents.length > 0) {
        this.formFieldsMap.get(formId).__config__.triggerEvents.forEach(triggerEventItem => {
          if (this.formFieldsMap.get(formId).__config__.triggerEventData && this.formFieldsMap.get(formId)
            .__config__.triggerEventData[triggerEventItem] && this.formFieldsMap.get(formId).__config__
            .triggerEventData[triggerEventItem].length > 0) {
            this.triggerEventHandler(this.formFieldsMap.get(formId).__config__.triggerEventData[
              triggerEventItem]);
          }
        });
      }
      return true;
    },
    //清空联想弹层、多选弹层的值
    clearBombLayerFormData(filed) {
      this.formData[filed] = '';
      this.formData[filed + '_showValue'] = '';
    },
    // 流程参数赋值
    processParameterAssignment() {
      // 流程中的流程参数赋值 优先级最高，最后赋值
      setTimeout(() => {
        if (this.isEdit != 2 && this.parameter && this.parameter[this.mainTableName]) {
          this.showForm = false;
          for (let [key, value] of Object.entries(this.parameter[this.mainTableName])) {
            this.setFormDataValue(key, value);
          }
          this.showForm = true;
        }
      }, 0);
    },
    setFormDataValue(field, val) {
      if (Array.isArray(this.formData[field])) {
        if (val.includes(',')) {
          this.formData[field] = val.split(',');
        }
        else {
          this.formData[field] = [val];
        }
      }
      else {
        this.formData[field] = val;
      }
      //处理联想弹层，多选弹层
      if (this.formData[field + '_showValue'] != undefined) {
        this.formData[field + '_showValue'] = val;
      }
    },
    setOutputsValue(nodeType, formId, res, outputKey) {
      let nodeTypeChecked = false;
      if (nodeType == 'created') {
        nodeTypeChecked = this.operationVal == 'add';
      }
      else if (nodeType == 'edit') {
        nodeTypeChecked = this.operationVal == 'edit';
      }
      else if (nodeType == 'mounted') {
        nodeTypeChecked = this.operationVal == 'add' || this.operationVal == 'edit';
      }
      if (nodeTypeChecked && this.disabled != true && res && res.data && res.data.data && this.formFieldsMap
        .has(formId) && this.formFieldsMap.get(formId).__vModel__ && this.formData.hasOwnProperty(this
          .formFieldsMap.get(formId).__vModel__)) {
        this.setFormDataValue(this.formFieldsMap.get(formId).__vModel__, res.data.data[outputKey]);
        // 联想弹层 多选弹层 特殊处理
        if (this.formFieldsMap.get(formId).__config__ && this.formFieldsMap.get(formId).__config__.avueType &&
          this.needShowValueTags.includes(this.formFieldsMap.get(formId).__config__.avueType)) {
          this.formData[this.formFieldsMap.get(formId).__vModel__ + '_showValue'] = res.data.data[outputKey];
        }
        this.triggerEventFormIdHandler(formId);
      }
    },
    //子表单权限
    getAuthorityTableChildrenList(bindTable, children) {
      let column = [];
      if (bindTable && this.formEnCodeList && this.formEnCodeList[bindTable]) {
        let formSubEnCodeList = this.formEnCodeList[bindTable];
        if (children && children.length > 0) {
          column = children.map(ele2 => {
            if (formSubEnCodeList.includes(ele2.prop)) {
              ele2.hide = false;
            }
            else {
              ele2.hide = true;
            }
            if (ele2.hide == false) {
              //工作流中系统表单必填权限
              if (this.formSubTableNotRequiredList && this.formSubTableNotRequiredList[bindTable] !=
                undefined) {
                if (this.formSubTableNotRequiredList[bindTable].includes(ele2.prop)) {
                  ele2.required = false;
                }
                else {
                  ele2.required = true;
                }
              }
              ele2.rules = [];
              if (ele2.required) {
                ele2.rules = ele2.ruleList;
              }
              // disabled 属性
              if (this.formSubTableDisabledList && this.formSubTableDisabledList[bindTable] !=
                undefined) {
                if (this.formSubTableDisabledList[bindTable].includes(ele2.prop)) {
                  ele2.disabled = true;
                }
                else {
                  ele2.disabled = false;
                }
              }
              if (this.disabled) { //查看
                ele2.disabled = true;
              }
            }
            else {
              ele2.rules = []
              if (ele2.required) {
                ele2.ruleList.forEach(el => {
                  el.message += ',' + this.$t('noFormAuth')
                })
                ele2.rules = ele2.ruleList;
              }
            }
            return ele2;
          });
        }
        return column;
      }
      else {
        return children;
      }
    },
    async insertCreatedEvent() {
      
    },
    async insertMountedEvent() {
      
    },
    async insertEditEvent() {
      
    },
    async insertSubmitEvent() {
      
    },
    getFormConfig() {
       return fieldsConfig();
    },
    getFormFieldsMap() {
       return formFieldsMap();
    },
    async getHideComponentsMap() {
      let mapList = new Map();
      let hideComponentList = this.getHideComponents();
      if (typeof this.initHideComponentList == 'function') {
        mapList = await this.initHideComponentList(hideComponentList);
        this.$store.commit("SET_HIDE_COMPONENT_LIST", mapList);
      }
      return mapList;
    },
    getHideComponentsMapItem(key) {
      if (this.hideComponentsMap.size > 0) {
        return this.hideComponentsMap.has(key) ? this.hideComponentsMap.get(key) : "";
      }
      else {
        return ""
      }
    },
    getHideComponents() {
       return getHideComponents();
    },
  }
}

</script>
<style>
.el-table__empty-block {
  width: 100% !important;
}

.avue-form__row {
  padding: 0 !important;
}

#editorphone {
  width: 375px;
  margin: 0 auto;
  border: 1px solid #E4E7ED;
  padding: 0 7.5px;
  background: #f5f6fa;
  height: 700px;
  overflow-y: auto;
  overflow-x: hidden;
  border-radius: 5px;
}

#editorphone .el-col {
  border-bottom: 1px solid #F2F2F2;
  background: #fff;
  margin-bottom: 0;
  padding: 0 15px 6px !important;
  width: 100%;
}

#editorphone .el-form-item__label {
  line-height: 20px
}

#editorphone .el-input-group .el-input__inner {
  background: #f5f6fa
}

#editorphone .el-input__inner {
  border: 0
}

#editorphone .el-input-group__append,
#editorphone .el-input-group__prepend {
  border: 0;
  background: #edeef2;
  color: #666;
}

#editorphone .el-input-group .el-input__prefix {
  left: 44px
}

#editorphone .el-input-group .el-input__suffix {
  right: 44px
}

#editorphone .el-form-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  flex-flow: wrap;
}

#editorphone .el-form-item__label {
  float: none;
  min-width: 85px;
  width: auto !important;
  text-align: left;
  flex: auto;
}

#editorphone .tinymce .el-form-item__label {
  min-width: 100%;
}

#editorphone .el-form-item__content {
  margin-left: 0px !important;
  flex: auto;
  width: calc(100% - 95px);
}

#editorphone .avueFormNoLable .el-form-item__label,
#editorphone .avueFormNoLable .avue-crud__pagination {
  display: none;
}

#editorphone .avueFormNoLable .el-collapse-item__wrap,
#editorphone .avueFormNoLable .el-collapse {
  border-bottom: 0
}

#editorphone .avueFormNoLable .el-col {
  border-bottom: 0;
  padding-bottom: 0
}

#editorphone .el-form-item__content .el-button:first-child {
  margin-left: 90px;
}

.el-upload__tip {
  line-height: 1.2;
}

</style>
